package cn.sciento.starter.tenant.custom.repository.impl;

import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;

import cn.sciento.common.STongService;
import cn.sciento.core.redis.RedisHelper;
import cn.sciento.core.redis.safe.SafeRedisHelper;
import cn.sciento.starter.tenant.custom.repository.TenantCustomPointRepository;

public class DefaultTenantCustomPointRepository implements TenantCustomPointRepository {
  private final RedisHelper redisHelper;
  
  private static final String CACHE_PREFIX = "hiam:tenant-custom:%s:%s";
  
  public DefaultTenantCustomPointRepository(RedisHelper redisHelper) {
    this.redisHelper = redisHelper;
  }
  
  public void saveTenantCustomPoint(@Nonnull String tenantNum, @Nonnull String serviceName, @Nonnull String customPointCode, @Nonnull Long priority) {
    SafeRedisHelper.execute(STongService.Iam.REDIS_DB, this.redisHelper, () -> this.redisHelper.zSetAdd(cacheKey(tenantNum, serviceName), customPointCode, priority.longValue()));
  }
  
  @NotNull
  public Set<String> listTenantCustomPoints(@Nonnull String tenantNum, @Nonnull String serviceName) {
    Set<String> set = SafeRedisHelper.execute(STongService.Iam.REDIS_DB, this.redisHelper, () -> this.redisHelper.zSetRange(cacheKey(tenantNum, serviceName), Long.valueOf(0L), Long.valueOf(-1L)));
    return Optional.ofNullable(set).orElse(Collections.emptySet());
  }
  
  @Nullable
  public Double getPriority(@Nonnull String tenantNum, @Nonnull String serviceName, @Nonnull String customPointCode) {
    return (Double)SafeRedisHelper.execute(STongService.Iam.REDIS_DB, this.redisHelper, () -> this.redisHelper.zSetScore(cacheKey(tenantNum, serviceName), customPointCode));
  }
  
  public void removeTenantCustomPoints(@Nonnull String tenantNum, @Nonnull String serviceName, @Nonnull String customPointCode) {
    SafeRedisHelper.execute(STongService.Iam.REDIS_DB, this.redisHelper, () -> this.redisHelper.zSetRemove(cacheKey(tenantNum, serviceName), customPointCode));
  }
  
  private String cacheKey(String tenantNum, String serviceName) {
    return String.format("hiam:tenant-custom:%s:%s", tenantNum, serviceName);
  }
}
